import { Inject, Injectable } from '@nestjs/common';
import { CreateAaa7Dto } from './dto/create-aaa7.dto';
import { UpdateAaa7Dto } from './dto/update-aaa7.dto';
import * as fs from 'fs';
import * as path from 'path';
const {MailParser} = require('mailparser')

@Injectable()
export class Aaa7Service {
  @Inject('MAIL_TRANSPORTER')
  transporter: any;

  @Inject('IMAP')
  imap: any;

  async sendMail() {
    const info = await this.transporter.sendMail({
      from: '"abin" <2313517435@qq.com>',
      to: 'ljb931122@163.com',
      subject: 'Hello 111',
      // text: "xxxxx"
      html: fs.readFileSync('public/test.html'),
    });

    console.log('邮件发送成功：', info.messageId);
    console.log(this.transporter);
  }

  async reveiveMail() {
    this.imap.once('ready', () => {
      this.imap.openBox('INBOX', true, (err) => {
        this.imap.search(
          [
            ['SEEN'],
            ['SINCE', new Date('2023-07-10 19:00:00').toLocaleString()],
          ],
          (err, results) => {
            if (!err) {
              this.handleResults(results)
            } else {
              throw err;
            }
          },
        );
      });
    });
    this.imap.connect();
  }

  handleResults(results) {
    this.imap.fetch(results, { 
        bodies: '',
    }).on('message', (msg) => {
        const mailparser = new MailParser();

        msg.on('body', (stream) => {

            const info = {
              theme: '',
              from: '',
              mailName: '',
              to: '',
              datatime: '',
              html: '',
              text: '',
            };
            stream.pipe(mailparser);

            mailparser.on("headers", (headers) => {
                info.theme = headers.get('subject');
                info.from = headers.get('from').value[0].address;
                info.mailName = headers.get('from').value[0].name;
                info.to = headers.get('to').value[0].address;
                info.datatime = headers.get('date').toLocaleString();
            });

            mailparser.on("data", (data) => {
                if (data.type === 'text') {
                    info.html = data.html;
                    info.text = data.text;
                    console.log(info);
                }
                if (data.type === 'attachment') {
                    const filePath = path.join(process.cwd(), 'public', data.filename);
                    const ws = fs.createWriteStream(filePath);
                    data.content.pipe(ws);
                }
            });
        });
    });
}

  create(createAaa7Dto: CreateAaa7Dto) {
    return 'This action adds a new aaa7';
  }

  findAll() {
    return `This action returns all aaa7`;
  }

  findOne(id: number) {
    return `This action returns a #${id} aaa7`;
  }

  update(id: number, updateAaa7Dto: UpdateAaa7Dto) {
    return `This action updates a #${id} aaa7`;
  }

  remove(id: number) {
    return `This action removes a #${id} aaa7`;
  }
}
